<template>
  <div class="page-container">
    <!-- 面包屑部分 -->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>红包</el-breadcrumb-item>
        <el-breadcrumb-item>红包活动列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters" :rules="filtersRules">
        <el-row class="search-input">
          <el-form-item prop="promName" label="活动名称：">
            <el-input clearable v-model="filters.promName" placeholder="活动名称" maxlength="80"></el-input>
          </el-form-item>
          <el-form-item prop="promotionId" label="活动ID：">
            <el-input clearable v-model="filters.promotionId" placeholder="活动ID"></el-input>
          </el-form-item>
          <el-form-item prop="creator" label="创建人：">
            <el-input clearable v-model="filters.creator" placeholder="创建人" maxlength="80"></el-input>
          </el-form-item>
          <el-form-item label="渠道：" prop="channelId">
            <el-select v-model="filters.channelId" placeholder="全部" clearable>
              <el-option
                v-for="item in channelOption"
                :key="item.id"
                :label="item.channelName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row class="times">
            <el-form-item label="活动时间：" prop="startTime">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="开始时间"
                class="input_postion"
                clearable
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
            <span class="times-to">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                  v-model="filters.endTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="结束时间"
                  class="input_postion"
                  clearable
                  @change="changeEndDate"
                  :picker-options="endDateDisabled"
                ></el-date-picker>
            </el-form-item>
          </el-row>
        </el-row>
        
        <el-row class="search-button">
          <el-form-item>
            <kt-button :label="$t('action.reset')" icon="el-icon-refresh" class="resetButton" @click="resetForm('filters')" />
          </el-form-item>
           <el-form-item>
            <kt-button icon="el-icon-search" label="搜索" @click="getPromotionList()" class="searchButton" />
          </el-form-item>
          <el-form-item>
            <kt-button label="创建活动" @click="createPage()" class="searchButton" perms="market:coupon:add"/>
          </el-form-item>
          <el-form-item>
            <kt-button label="通过模板添加活动" @click="createCouponTemplate()" class="searchButton" perms="market:coupon:temp"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="tab-container">
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="item in tabMapOptions"
          :key="item.key"
          :label="item.label"
          :name="item.key"
        >
        </el-tab-pane>
        <!-- tab表格 -->
        <el-table
          :data="tableData" 
          :highlight-current-row="true"
          :max-height="1500"
          :size="size"
          v-loading="loading"
          :align="align"
          style="width: 100%">
        <el-table-column
          align="center"
          prop="promotionId"
          label="活动ID"
          width="300">
        </el-table-column>
        <el-table-column
          align="center"
          prop="promName"
          label="红包名称"
          width="240">
        </el-table-column>
        <!-- <el-table-column
          align="center"
          prop="channelCodess"
          label="活动渠道"
          width="240">
        </el-table-column> -->
          <el-table-column align="center" label="使用条件" width="240">
              <template slot-scope="scope">
                  满 {{scope.row.useTotalAmountLimit}} 元可用
              </template>
          </el-table-column>
          <el-table-column align="center" label="红包面值" width="240">
              <template slot-scope="scope">
                  {{scope.row.couponAmount}} 元
              </template>
          </el-table-column>
          <el-table-column align="center" label="总限额(张)" width="240">
              <template slot-scope="scope">
                    {{scope.row.idLimitNum == null || scope.row.idLimitNum == '' ? "无限制" : scope.row.idLimitNum}}
              </template>
          </el-table-column>
          <el-table-column align="center" label="每人限领（张）" width="240">
            <template slot-scope="scope">
                  {{scope.row.idLimitDayNum == null || scope.row.idLimitDayNum == '' ? "无限制" : scope.row.idLimitDayNum}}
            </template>
          </el-table-column>
        <el-table-column
          align="center"
          label="开始时间/结束时间"
          width="360">
           <template slot-scope="scope">
              <span v-if="scope.row.startTime != null && scope.row.endTime != null">{{scope.row.startTime}}至{{scope.row.endTime}}</span>
           </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="address"
          label="活动状态"
          width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 9">活动草稿</span>
            <span v-else-if="statusFormat(scope.row) == 11">待提交</span>
            <span v-else-if="statusFormat(scope.row) == 12">待审核</span>
            <span v-else-if="statusFormat(scope.row) == 13">未开始</span>
            <span v-else-if="statusFormat(scope.row) == 14">审核未通过</span>
            <span v-else-if="statusFormat(scope.row) == 15">进行中</span>
            <span v-else-if="statusFormat(scope.row) == 16">已过期</span>
            <span v-else-if="statusFormat(scope.row) == 17">已结束</span>
            <span v-else-if="scope.row.status == 7">已关闭</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="creatorName"
          label="创建人"
          width="240">
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="290">
        </el-table-column>
        <el-table-column
          align="left"
          fixed="right"
          label="操作"
          width="390">
          <template slot-scope="scope">
            <el-button type="text" @click="handleClick(scope.row)" v-if="scope.row.status != 9" size="mini" style="">查看</el-button>
            <kt-button type="text" size="mini" v-if="scope.row.status == 9 || statusFormat(scope.row) == 11 || statusFormat(scope.row) == 14" v-show="scope.row.editFlag" @click="editInfo(scope.row)" perms="market:coupon:edit" label="编辑"/>
            <kt-button type="text" size="mini" v-if="statusFormat(scope.row) == 11 || scope.row.status == 9" v-show="scope.row.editFlag" @click="deleteInfo(scope.row)" perms="market:coupon:delete" label="删除"/>
            <kt-button type="text" size="mini" v-if="scope.row.status != 9" @click="copyInfo(scope.row)" v-show="scope.row.editFlag" perms="market:coupon:copy" label="复制"/>
            <kt-button type="text" size="mini" v-if="statusFormat(scope.row) == 13 || statusFormat(scope.row) == 15" v-show="scope.row.editFlag" @click="closeInfo(scope.row)" perms="market:coupon:close" label="关闭"/>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          class="t_r"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="filters.start"
          :page-sizes="[10, 20, 50, 100 ,300 , 500]"
          :page-size="filters.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
      </el-tabs>
    </div>
    <!--弹出框-->
    <el-dialog title="请选择秒杀/拼团/满额促销形式" :visible.sync="flag" class="el-dialog-form" >
      <div class="flex mb20">
        <p class="form-left-width">活动类型：</p>
        <el-select v-model="form.region" placeholder="请选择秒杀/拼团/满额促销形式">
          <el-option label="秒杀" value="one"></el-option>
          <el-option label="拼团" value="two"></el-option>
          <el-option label="满额促销" value="three"></el-option>
        </el-select>
      </div>
      <div class="flex mb20">
        <p class="form-left-width">当前参与用户：</p>
        <el-checkbox-group v-model="joinCheck">
          <el-checkbox v-for="item in joinList" :label="item" :key="item" class="mr20"></el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="flex mb20">
        <p class="form-left-width">推送方式：</p>
        <el-checkbox-group v-model="wayCheck">
          <el-checkbox v-for="item in wayList" :label="item" :key="item" class="mr20"></el-checkbox>
        </el-checkbox-group>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button class="cancelButton" plain @click="flag = false" >取 消</el-button>
        <el-button class="searchButton" @click="checked">提交</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="couponTemplatedialogVisible"  title="使用模板">
      <el-form :inline="true" class="mb30" size="small" v-model="templateDataForm" ref="templateDataForm" :rules="templateDataFormRules">
        <el-form-item label="ID：" class="w178">
          <el-input clearable v-model="templateDataForm.id" placeholder="ID"></el-input>
        </el-form-item>
        <el-form-item label="名称：" class="w178">
          <el-input clearable v-model="templateDataForm.templateName" placeholder="名称" maxlength="80"></el-input>
        </el-form-item> 
        <el-form-item>
          <el-button class="searchButton" icon="el-icon-search" @click="queryTemplateList">搜索</el-button>
        </el-form-item> 
      </el-form>
      <div class="table-section">
        <el-table
          :data="templateTableData"
          v-loading="templateLoading"
          :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
          :highlight-current-row="true"
          ref="multipleTable"
          style="width: 100%"
          :size="size"
        >
          <el-table-column
            prop="id"
            label="ID"
            align="center">
          </el-table-column>
          <el-table-column
            align="center"
            prop="promType"
            label="活动类型">
            <template>
              <span>红包</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="templateName"
            label="模板名称">
          </el-table-column>
          <el-table-column
            align="center"
            prop="creatorName"
            label="创建人">
          </el-table-column>
          <el-table-column
            align="center"
            prop="createTime"
            label="创建时间"
            width="200">
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="150">
            <template slot-scope="scope">
              <el-button @click="used(scope.row)" type="text" class="textButton" size="small">使用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="templateTableData.length > 0" style="float: right;margin-top: 20px;" >
        <el-pagination
          @size-change="templatehandleSizeChange"
          @current-change="templatehandleCurrentChange"
          :current-page="templateDataForm.start"
          :page-sizes="[10]"
          :page-size="templateDataForm.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="templateListTotal"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  front_prom_types,
  chanel_codes,
  prom_types
} from "@/market/dict/marketDict";
import KtButton from "@/views/Core/KtButton";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from "color-name";
import tabPane from "./components/TabPaneSeckill";
import {channelCodeConverter} from "@/market/dict/marketDict";

export default {
  name: "Tab",
  components: {
    tabPane,
    KtButton,
    TableColumnFilterDialog
  },
  data() {
    return {
      channelOption:[],
      templateDataFormRules:{
        //templateName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },
      filtersRules: {
        // promName: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
        // creator: { min: 0, max: 80, message: "字数0-80个字符", trigger: "blur" },
      },
      pageNumber:1,
      pageSize:10,
      total:0,
      loading:false,
      align:"center",
      tableData: [],
      flag: false,
      form: {
        region: ""
      },
      option1: 1,
      option1: 2,
      option1: 3,
      tabMapOptions: [
        { label: '全部', key: '99' },
        { label: '进行中', key: '5' },
        { label: '已结束', key: '8' },
        { label: '已过期', key: '6' },
        { label: '已关闭', key: '7' },
        { label: '未开始', key: '3' },
        { label: '待提交', key: '1' },
        { label: '待审核', key: '2' },
        { label: '审核未通过', key: '4' },
        { label: '活动草稿', key: '9' },
      ],
      activeName: "99",
      createdTimes: 0,
      size: "small",
      filters: {
        promName: null,
        id: "",
        promType: 12,
        channelCode: "",
        activityType: "",
        merchantId: null,
        creator: "",
        startTime: "",
        endTime: "",
        operatorStoreId: null,
        type: "",
        status: null,
        t: "sysConfig",
        queryname: "",
        start:1,
        limit: 10
      },
      frontPromTypes: this.getFrontPromType(),
      promTypes: this.getPromType(),
      channelCodes: chanel_codes,
      activityTypes: [
        { activityType: "", label: "请选择" },
        { activityType: "0", label: "自建" },
        { activityType: "1", label: "报名" }
      ],
      merchantIds: [{ merchantId: null, label: "请选择" }],
      storeIds: [{ storeId: null, label: "请选择" }],
      joinCheck: [],
      joinList: ["已使用用户", "未使用用户"],
      wayCheck: [],
      wayList: ["短信", "小程序", "网站", "H5", "邮件"],

      couponTemplatedialogVisible: false,        //活动模板弹窗
      templateDataForm: {
        start: 1,
        limit: 10,
        promType: 12,  //红包
      },                     //模板搜索条件
      templateTableData:[],                     //模板List
      templateLoading: false,                   //模板table加载状态
      templateListTotal: 0,                     //模板LIst总条数
      tabsIndex: "first",

      startDateDisabled: {},//开始时间限制
      endDateDisabled: {},//结束时间限制
    };
  },
  methods: {
    queryChannelListOther: function() {
      var this_ = this;
      this.utils.request.queryChannelListOther({}, function(res) {
        if (res.code == "0000") {
          this_.channelOption = res.data;
        }
      });
    },
    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.startTime) {
            return time.getTime() <= new Date(this_.filters.startTime).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.endTime) {
            return time.getTime() >= new Date(this_.filters.endTime).getTime();
          }
        }
      };
    },

    /**
     * 状态格式化
     */
    statusFormat(row){
      if(row.status == 1 && new Date().getTime() <= new Date(row.startTime).getTime()){
        //待提交
          return 11;
      }else if(row.status == 2 && new Date().getTime() <= new Date(row.startTime).getTime()){
        //待审核
        return 12;
      }else if(row.status == 11 && new Date().getTime() <= new Date(row.startTime).getTime()){
        //未开始
        return 13;
      }else if(row.status == 4 && new Date().getTime() <= new Date(row.startTime).getTime()){
        //审核未通过
        return 14;
      }else if(row.status == 11 && new Date().getTime() >= new Date(row.startTime).getTime() && new Date().getTime() <= new Date(row.endTime).getTime()){
        //进行中
        return 15;
      }else if((row.status == 1 || row.status ==  2 || row.status == 4) && new Date().getTime() > new Date(row.startTime).getTime()){
        //已过期
        return 16;
      }else if(row.status == 11 && new Date().getTime() > new Date(row.endTime).getTime()){
        //已结束
        return 17;
      }
    },
    /**
     * 根据活动模板创建优惠券
     */
    createCouponTemplate(){
      this.couponTemplatedialogVisible = true;
      this.tempPageQuery()
    },
    /**
     * 使用模板
     */
    used(row){
      const loading = this.$loading({
        lock: true,
        text: '小的正在加载中,请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.utils.request.couponCopyConfig({promotionId:row.promotionId},res=>{
        loading.close();
        if(res.code == '0000'){
          this.couponTemplatedialogVisible = false;
          this.$router.push({path:"/RedEnvelopeComponents/"+res.data+"/1"})
        }else{
          this.$message({message:res.msg,type:'error'});
        }
      })
    },
    /**
     * 搜索模板
     */
    queryTemplateList(){
       this.$set(this.templateDataForm,"start",1);
       this.tempPageQuery()
    },
    /**
     * 分页数据切换
     */
    templatehandleSizeChange(){

    },
    /**
     * 页码切换
     */
    templatehandleCurrentChange(){
      this.tempPageQuery()
    },
    /**
     * 查询模板数据
     */
    // 分页查询
    tempPageQuery() {
      this.templateLoading = true;
      let callback = res => {
        this.templateLoading = false;
        if (res.code == "0000") {
          this.templateTableData = res.data.rows;
          this.templateListTotal = res.data.total;
        }else{
          this.$message({ message: "查询失败", type: "fail" });
        }
      };
      this.utils.request.templatePageQuery(this.templateDataForm, callback);
    },
    /**
     * 编辑
     */
    editInfo(row){
      this.$router.push({path:"/RedEnvelopeComponents/"+row.promotionId+"/1"})
    },
    /**
     * 删除
     */
    deleteInfo(row){
      let that = this;
      this.$confirm("确定要执行删除操作么？删除后不可恢复!", "提示", {
          type: "warning"
      }).then(() => {
          this.utils.request.couponDeleteConfig({promotionId:row.promotionId},res=>{
            that.$message({message:"删除成功",type:'success'});
            that.findPage();
          })
      }).catch(() => {});
    },
    /**
     * 复制
     */
    copyInfo(row){
      let that = this;
      this.$confirm("确定要复制该活动？", "提示", {
          type: "warning"
      }).then(() => {
          this.utils.request.couponCopyConfig({promotionId:row.promotionId},res=>{
            that.$message({message:"复制成功",type:'success'});
            that.findPage();
          })
      }).catch(() => {});
    },
    /**
     * 关闭
     */
    closeInfo(row){
      let that = this;
      let flag = "正在进行中";
      if(row.status == '3'){
        flag = "即将进行";
      }
       this.$confirm("该活动"+flag+"，确定要关闭它？关闭后不可再次开启。", "提示", {
          type: "warning"
      }).then(() => {
        this.utils.request.couponCloseConfig({promotionId:row.promotionId},res=>{
          that.$message({message:"关闭成功",type:'success'});
          that.findPage();
        })
      }).catch(() => {});

    },
    handleClick(row){
      this.$router.push({path:"/RedEnvelopeDetail" , query:{"promotionId":row.promotionId}})
    },
    handleSizeChange(val) {
      this.$set(this.filters,"limit",val);
      this.findPage();
    },
    handleCurrentChange(val) {
      this.$set(this.filters,"start",val);
      this.findPage();
    },
    findPage(){
      let that = this;
      this.loading = true;

      this.filters.merchantId = this.filters.merchantId == '' ? null : this.filters.merchantId;
      this.filters.operatorStoreId = this.filters.operatorStoreId == '' ? null : this.filters.operatorStoreId;

      this.filters.status = this.filters.status == '99' ? null : this.filters.status;
      this.utils.request.couponQueryConfigPage(this.filters,res=>{
        that.loading = false;
        that.tableData = res.data.rows; 
        that.total = res.data.total;

      })
    },

    genChannelCode: function(code) {
      return channelCodeConverter(code);
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },

    resetForm(formName) {

      //需要校验的keys
      let keys = ["creator","promotionId","promName","startTime","endTime","channelId"]
      //调用校验
      let  boo = this.seachTableUtils.checkFromIsNull(this.filters,keys)
      if(!boo){
        return;
      }
      

      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
      }
      this.$set(this.filters,"start",1);
      this.$set(this.filters,"limit",10);
      this.findPage();
    },
    createPage() {
      this.$router.push("/RedEnvelopeComponents/0/1");
      // this.$router.push("/CreatePromotion"+"?auth=1");
    },
    getPromotionList() {
      this.$set(this.filters,"start",1);
      this.$set(this.filters,"limit",10);
      this.findPage();
      // this.$refs.child[0].listQuery.pageNo = 1;
      // this.$refs.child[0].getList();
    },
    changeMerchant() {
      let this_ = this;
      this.utils.request.queryStoreList(
        { start: 1, limit: 10000000, merchantId: this.filters.merchantId },
        function(res) {
          if (res.code == "0000") {
            res.data.rows.forEach(item => {
              //,{'storeId':'0','label':'张小二bbc店铺'},{'storeId':'1','label':'张小二的京东店'}
              let store = {};
              store.storeId = item.id;
              store.label = item.storeName;
              this_.storeIds.push(store);
            });
          }
        }
      );
    },
    getFrontPromType: function(row, column, cellValue, index) {
      return front_prom_types.filter(e => {
        return e.code == "skill_front_prom_type";
      });
    },

    getPromType: function(row, column, cellValue, index) {
      return prom_types.filter(e => {
        return e.code == "skill_promotion";
      });
    },
    checked() {
      this.flag = false;
      if (this.form.region == "one") {
        this.$router.push("/SeckillPromotionEvent" + "?auth=0");
      } else if (this.form.region == "two") {
        this.$router.push("/GroupActivityComponents?auth=0");
      } else {
        this.$router.push("/CreatePromotion3");
      }
    },
    SecondSell() {
      this.flag = true;
    }
  },
  watch: {
    activeName(val) {
      this.filters.status = val == '0' ? '' : val;
      this.$set(this.filters,"start",1);
      this.$set(this.filters,"limit",10);
      this.findPage();
    }
  },
  created() {
    //获取商家列表
    const tab = this.$route.query.tab;
    if (tab) {
      this.activeName = tab;
    }
  },
  mounted() {
    //查询列表
    this.findPage();
    this.queryChannelListOther();
  }
};
</script>

<style scoped lang="scss">
 
</style>
